package com.fjzx.frame.page;

import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.fjzx.androidframe.base.annotation.ContentView;
import com.fjzx.androidframe.base.annotation.ViewModel;
import com.fjzx.androidframe.base.fragment.BaseFragment;
import com.fjzx.androidframe.base.widget.xrecyclerview.XRecyclerView;
import com.fjzx.frame.R;
import com.fjzx.frame.adapter.HomeListAdapter;
import com.fjzx.frame.viewmodel.HomeViewModel;

import butterknife.BindView;

/**
 * @author xiongyongcong
 */
@ViewModel(HomeViewModel.class)
@ContentView(R.layout.fragment_home)
public class HomeFragment extends BaseFragment<HomeViewModel> {
    @BindView(R.id.xrv_list)
    XRecyclerView xrvList;

    private HomeListAdapter mAdapter;

    @Override
    protected void initView(View view) {
        mAdapter = new HomeListAdapter();
        xrvList.setLayoutManager(new LinearLayoutManager(mActivity));
        xrvList.setAdapter(mAdapter);
        xrvList.setOnPullLoadMoreListener(new XRecyclerView.SimplePullLoadMoreListener() {
            @Override
            public void onRefresh() {
                mAdapter.refresh();
            }
        });
    }

    @Override
    protected void initData() {
        mViewModel.homeArticalLiveData.observe(this, resource -> handleResult(resource));
        mViewModel.getHomeArticals().observe(this, data -> mAdapter.submitList(data));
    }

    @Override
    protected void handleLoading(String action, int msgId) {
        xrvList.setRefreshing(true);
    }

    @Override
    protected void handleError(String action, String message) {
        if (mAdapter.getCurrentList() == null || mAdapter.getCurrentList().isEmpty()) {
            xrvList.showError(message);
        } else {
            super.handleError(action, message);
        }
    }

    @Override
    protected <T> void handleSuccess(String action, T data) {
        xrvList.setRefreshing(false);
        if (data == null) {
            if (mAdapter.getCurrentList() == null || mAdapter.getCurrentList().isEmpty()) {
                xrvList.showEmpty();
            } else {
                xrvList.setHasMore(false);
            }
        }
    }
}
